package com.ndood.admin.core.web.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class TimeInterceptor implements HandlerInterceptor{
	
	/**
	 * preHandle
	 * 控制器方法调用前调用
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//System.out.println("preHandle");
		//System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
		//System.out.println(((HandlerMethod)handler).getMethod().getName());
		request.setAttribute("startTime", new Date().getTime());
		// 决定是否访问控制器方法
		return true;
	}

	/**
	 * postHandle
	 * 控制器方法调用后调用，如果控制器方法抛出异常则不会调用
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView arg3)
			throws Exception {
		System.out.println("postHandle");
		Long start = (Long) request.getAttribute("startTime");
		request.setAttribute("time interceptor 耗时:", (new Date().getTime()-start));
	}

	/**
	 * afterCompletion
	 * 不管控制器方法是否异常都调用
	 * 如果获取不到异常，可能是被ControllerExceptionHandler处理掉了
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("afterCompletion");
		Long start = (Long) request.getAttribute("startTime");
		request.setAttribute("time interceptor 耗时:", (new Date().getTime()-start));
		System.out.println("ex is " + ex);
	}
	
}